<template>
  <!--  查询区-->
  <div class="search">
    <el-form inline :model="reserveSearchModel" ref="reserveSearchForm">
      <el-form-item label="会员: ">
        <el-input v-model="reserveSearchModel.member" placeholder="请输入会员姓名"/>
      </el-form-item>
      <el-form-item label="课程: ">
        <el-input v-model="reserveSearchModel.course" placeholder="请输入课程名称"/>
      </el-form-item>
      <el-form-item label="状态: ">
        <el-select v-model="reserveSearchModel.status" placeholder="请选择状态" clearable style="width: 150px">
          <el-option label="已预约" value="1"/>
          <el-option label="已取消" value="2"/>
          <el-option label="已完成" value="3"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="search()">查询</el-button>
        <el-button type="primary" :icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!--  按钮区-->
<!--  <div class="action">-->
<!--    <el-button type="primary" :icon="Delete" @click="remove">删除</el-button>-->
<!--  </div>-->

  <!--  表格区-->
  <div class="grid">
    <el-table :data="reserve"
              stripe
              border
              @row-click="tblRowClick"
              ref="tblRef"
              style="width: 100%">
      <el-table-column type="selection" align="center" width="55"/>
      <el-table-column prop="id" label="编号" align="center" width="80"/>
      <el-table-column prop="memberName" label="会员" width="120"/>
      <el-table-column prop="courseName" label="课程" width="120"/>
      <el-table-column prop="coachName" label="教练" width="120"/>
      <el-table-column prop="courseTime" label="上课时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.courseTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="length" label="时长(分钟)" width="100"/>
      <el-table-column prop="reserveTime" label="预约时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.reserveTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="score" label="评分" width="80"/>
      <el-table-column prop="comment" label="评语" width="150" show-overflow-tooltip/>
      <el-table-column prop="commentTime" label="评价时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.commentTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ formatStatus(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160" align="center" fixed="right">
        <template #default="scope">
          <el-button
              type="danger"
              size="small"
              @click.stop="cancelReserve(scope.row)"
              :disabled="scope.row.status !== '1'">
            取消预约
          </el-button>
          <el-button
              type="primary"
              size="small"
              @click.stop="editReserve(scope.row)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!--  分页区-->
  <div class="pagination">
    <el-pagination
        v-model:current-page="reservePi.pageNo"
        v-model:page-size="reservePi.pageSize"
        layout="prev, pager, next, jumper, ->, total"
        :total="reservePi.total"
        @current-change="handlePageChange"/>
  </div>
  <!--  弹窗区-->
  <el-dialog :title="coachDlgTiele" v-model="coachDlgShow" draggable align-center :close-on-click-modal="false"
             @close="resetCoachForm">
    <el-form :model="reserveModel" ref="coachFormRef" label-width="100px" label-position="right">

      <el-form-item label="课程名称：" prop="courseId">
        <el-select
            v-model="reserveModel.courseId"
            placeholder="请选择课程"
            clearable
            filterable
            style="width: 100%">
          <el-option
              v-for="course in courseList"
              :key="course.id"
              :label="course.name"
              :value="course.id">
            <span>{{ course.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              {{ formatDateTime(course.time) }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div>
        <el-button @click="coachDlgShow=false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue"
import api from "@/utils/api.js"
import {Delete, Refresh, Search} from "@element-plus/icons-vue"
import {ElMessage, ElMessageBox} from "element-plus"

// 表格数据
let reserve = ref([])

// 表格引用
let tblRef = ref()

// 分页数据
let reservePi = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

// 弹窗相关
let coachDlgShow = ref(false)
let coachDlgTiele = ref("修改预约信息")
let coachFormRef = ref()

// 课程列表数据
let courseList = ref([])

// 预约表单数据
let reserveModel = ref({
  id: null,
  memberId: null,
  courseId: null,
  memberName: '',
  courseName: '',
  coachName: '',
  courseTime: '',
  reserveTime: '',
  status: '',
  score: null,
  comment: ''
})

// 查询条件
let reserveSearchModel = ref({
  member: "",
  course: "",
  status: ""
})

// 格式化日期时间
function formatDateTime(dateTimeString) {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化状态显示
function formatStatus(status) {
  const statusMap = {
    '1': '已预约',
    '2': '已取消',
    '3': '已完成'
  }
  return statusMap[status] || status
}

// 获取状态标签类型
function getStatusTagType(status) {
  const typeMap = {
    '1': 'primary',
    '2': 'danger',
    '3': 'success'
  }
  return typeMap[status] || 'info'
}

// 获取课程列表
async function getCourseList() {
  try {
    let resp = await api({
      url: "/course",
      method: "get",
      params: {
        pageNo: 1,
        pageSize: 999 // 获取所有课程
      }
    })

    if (resp && resp.success) {
      courseList.value = resp.data.records || []
    }
  } catch (error) {
    console.error("获取课程列表失败:", error)
    ElMessage.error("获取课程列表失败")
  }
}

// 查询预约数据
async function search(pageNo = 1, pageSize = 7, params) {
  try {
    // 构建正确的查询参数，与后端 Reserve 实体类属性名保持一致
    params = {
      memberName: reserveSearchModel.value.member?.trim(),
      courseName: reserveSearchModel.value.course?.trim(),
      status: reserveSearchModel.value.status
    }

    // 发送请求
    let resp = await api({
      url: "/reserve",
      method: "get",
      params: {
        pageNo,
        pageSize,
        ...params
      },
    })

    console.log("查询预约数据:", params, resp);

    if (resp && resp.success) {
      // 安全地处理返回的数据
      reserve.value = (resp.data.records || []).map(item => {
        // 为每个可能为undefined的对象提供默认值
        const member = item.member || {}
        const course = item.course || {}
        const coach = item.coach || {}

        return {
          id: item.id,
          memberName: member.name || '',
          courseName: course.name || '',
          coachName: coach.name || '',
          courseTime: course.time,
          length: course.length,
          reserveTime: item.reserveTime,
          score: item.score,
          comment: item.comment,
          commentTime: item.commentTime,
          status: String(item.status || '')
        }
      })

      reservePi.total = resp.data.total
      reservePi.pageNo = resp.data.current
      reservePi.pageSize = resp.data.size
    } else {
      ElMessage.error(resp?.message || '查询失败')
    }
  } catch (error) {
    console.error("查询预约数据失败:", error)
    // 更安全的错误处理
    if (error.response) {
      ElMessage.error(`查询失败: ${error.response.status} ${error.response.statusText}`)
    } else if (error.request) {
      ElMessage.error('网络连接失败，请检查服务器是否正常运行')
    } else {
      ElMessage.error('查询请求配置错误')
    }
  }
}

// 重置查询条件
function reset() {
  reserveSearchModel.member = ""
  reserveSearchModel.course = ""
  reserveSearchModel.status = ""
  reservePi.pageNo = 1
  search()
}

// 表格行点击
function tblRowClick(row) {
  tblRef.value.toggleRowSelection(row)
}

// 分页改变
function handlePageChange(pageNo, pageSize) {
  search(pageNo, pageSize)
}

// 取消预约
function cancelReserve(row) {
  ElMessageBox.confirm(`确定要取消预约"${row.memberName}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      let resp = await api({
        url: `/reserve/${row.id}/cancel`,
        method: "post"
      })
      if (resp && resp.success) {
        ElMessage.success('取消预约成功')
        search()
      } else {
        ElMessage.error(resp?.message || '取消预约失败')
      }
    } catch (error) {
      console.error("取消预约失败:", error)
      ElMessage.error('取消预约失败')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 编辑预约
async function editReserve(row) {
  // 填充表单数据
  reserveModel.value = {
    id: row.id,
    memberId: null, // 如果需要可以添加会员ID
    courseId: null, // 课程ID将在下拉框中选择
    memberName: row.memberName,
    courseName: row.courseName,
    coachName: row.coachName,
    courseTime: formatDateTime(row.courseTime),
    reserveTime: formatDateTime(row.reserveTime),
    status: row.status,
    score: row.score,
    comment: row.comment
  }

  coachDlgShow.value = true
}

// 提交编辑
async function submitEdit() {
  try {
    // 构建提交数据
    const submitData = {
      id: reserveModel.value.id,
      courseId: reserveModel.value.courseId,
      status: reserveModel.value.status,
      score: reserveModel.value.score,
      comment: reserveModel.value.comment
    }
    let resp = await api({
      url: "/reserve",
      method: "put",
      data: submitData
    })

    if (resp && resp.success) {
      ElMessage.success('修改成功')
      coachDlgShow.value = false
      search()
    } else {
      ElMessage.error(resp?.message || '修改失败')
    }
  } catch (error) {
    console.error("修改预约失败:", error)
    ElMessage.error('修改预约失败')
  }
}

// 重置表单
function resetCoachForm() {
  // 安全地调用 resetFields 方法
  if (coachFormRef.value) {
    coachFormRef.value.resetFields()
  }
}

// todo:删除预约
function remove() {
  let rows = tblRef.value.getSelectionRows()
  if (rows.length === 0) {
    ElMessage.warning("请选择要删除的预约记录")
    return
  }

  ElMessageBox.confirm(`确定要删除选中的${rows.length}条预约记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = rows.map(row => row.id)
      let resp = await api({
        url: "/reserve",
        method: "delete",
        data: ids
      })
      if (resp && resp.success) {
        ElMessage.success('删除成功')
        search()
      } else {
        ElMessage.error(resp?.message || '删除失败')
      }
    } catch (error) {
      console.error("删除预约失败:", error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

onMounted(() => {
  search()
  getCourseList() // 获取课程列表
})
</script>

<style scoped>
.search {
  padding: 20px;
  background: white;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.search .el-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  position: sticky;
  top: 0;
  z-index: 10000;
}

.search .el-form-item {
  margin-bottom: 0;
}

.action {
  padding: 10px 20px;
  background: white;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 84px;
  z-index: 99;
}

.grid {
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.el-table {
  margin-top: 10px;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.el-table :deep(th.el-table__cell) {
  background-color: #f5f7fa;
  color: #333;
  font-weight: 500;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 15px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.el-button {
  transition: all 0.3s;
}

.el-button + .el-button {
  margin-left: 12px;
}

.el-button--primary {
  background-color: #1e3c72;
  border-color: #1e3c72;
}

.el-button--primary:hover {
  background-color: #2a5298;
  border-color: #2a5298;
}

.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.el-button--danger:hover {
  background-color: #f78989;
  border-color: #f78989;
}

.el-input__inner,
.el-textarea__inner {
  border-radius: 4px;
}
</style>
